package com.servlet.useraction;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.database.connection.DatabaseConnection;

@WebServlet("/UserChangePassword")
public class ChangePasswordServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String confirmOldPass = req.getParameter("txtOldPassword");
		String newPass = req.getParameter("txtNewPassword");
		String confirmNewPass = req.getParameter("txtConfirmNewPassword");
		String userName = (String) req.getSession().getAttribute("userName");
		String password = (String) req.getSession().getAttribute("password");
		
		Connection conn = null;
		PreparedStatement stmt = null;
		String sql = "update user " + 
					 "set Password=? where UserName=?";
		if (!confirmOldPass.equals(password)) {
			req.setAttribute("message", "You entered wrong password. Please try again");
			req.getRequestDispatcher("ChangePasswordForm.jsp").forward(req, resp);
		} else if (!newPass.equals(confirmNewPass)) {
			req.setAttribute("message", "Confirm password mismatch. Please try again");
			req.getRequestDispatcher("ChangePasswordForm.jsp").forward(req, resp);
		} else {
			try {
				conn = DatabaseConnection.getConnection();
				stmt = conn.prepareStatement(sql);
				stmt.setString(1, newPass);
				stmt.setString(2, userName);
				stmt.executeUpdate();
				req.getSession().setAttribute("password", newPass);
				
				stmt.close();
				conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
	}
}
